package org.cloudie.docs.editor.client.extended;

import com.google.gwt.core.client.JavaScriptObject;

public class FileUploader extends JavaScriptObject {

  public static FileUploader getInstance() {
	return JavaScriptObject.createObject().cast();
  }
	
  protected FileUploader() {}

  public final native int getProgress() /*-{
    return this.progress || 0;
  }-*/;

  public final native void setProgress(int progress) /*-{
    this.progress = progress;
  }-*/;

  public final native String getStatus() /*-{
    return this.status;
  }-*/;

  public final native void setStatus(String status) /*-{
    this.status = status;
  }-*/;

  public final native void uploadFile(String url, File file,
	    Runnable loadHandler, Runnable progressHandler,
	    Runnable errorHandler) /*-{
	var handler = this;
	xhr = new XMLHttpRequest(),
	getBinaryDataReader = new $wnd.FileReader(),
	fileUpload = xhr.upload;

    fileUpload.addEventListener("progress", function(event) {
      if (event.lengthComputable) {
		handler.progress = Math.round((event.loaded * 100) / event.total);
		if (progressHandler) progressHandler.@java.lang.Runnable::run()();
	  }
    }, false);
    fileUpload.addEventListener("load", function(event) {
      if (loadHandler) loadHandler.@java.lang.Runnable::run()();
    }, false);
    fileUpload.addEventListener("error", function(error) {
      handler.status = error;
      if (errorHandler) errorHandler.@java.lang.Runnable::run()();
    }, false);

    xhr.open("POST", url);
    xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');

    getBinaryDataReader.addEventListener("loadend", function(evt){ xhr.sendAsBinary(evt.target.result);}, false);
    getBinaryDataReader.readAsBinaryString(file);
	
  }-*/;

}
